from docx import Document
import re
from config import ENDING_PUNCTUATION_MAP, CHINESE_QUOTES, ABBREVIATIONS

def ends_with_punctuation(text):
    """检查文本是否以结束符号结尾（包括被引号包围的情况）"""
    end_punctuations = {'.', '。', '?', '？', '!', '！'}
    quote_chars = {'"', "'", "“", "”", "‘", "’"}

    i = len(text) - 1
    while i >= 0:
        char = text[i]
        if char in end_punctuations:
            return True
        elif char in quote_chars:
            i -= 1
        else:
            return False
    return False

def read_paragraphs(file_path, max_paragraphs=0):
    """读取文档的非空段落（合并未结束的段落）"""
    doc = Document(file_path)
    raw_paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]

    merged_paragraphs = []
    current_para = ""

    for para in raw_paragraphs:
        if not current_para:
            current_para = para
        else:
            current_para += " " + para

        if ends_with_punctuation(current_para):
            merged_paragraphs.append(current_para)
            current_para = ""
            if max_paragraphs > 0 and len(merged_paragraphs) >= max_paragraphs:
                break

    if current_para and (max_paragraphs <= 0 or len(merged_paragraphs) < max_paragraphs):
        merged_paragraphs.append(current_para)

    return merged_paragraphs